<?php

namespace app\admin\model;

use app\admin\validate\Shop as ValidateShop;
use think\Model;

class Shop extends Model
{
    public function getshoplist($data)
    {
        $result = db("shop")
            ->alias("s")
            ->join("app a", "a.appid=s.appid")
            ->where("s.name", "like", "%{$data['shopname']}%")
            ->field("s.*,a.appname")
            ->limit($data["limit"])->page($data["page"])
            ->order($data['sort'], $data['sortOrder'])
            ->select();
        $count = db("shop")
            ->alias("s")
            ->join("app a", "a.appid=s.appid")
            ->where("s.name", "like", "%{$data['shopname']}%")
            ->field("s.*,a.appname")
            ->count();
        return json(["rows" => $result, "total" => $count]);
    }

    public function add($data)
    {
        $validate = new ValidateShop();
        if(!$validate->scene('add')->check($data)){
            return $validate->getError();
        }
        $data["createtime"] = date("Y-m-d H:i:s",time());
        $result = $this->allowField(true)->save($data);
        if($result > 0){
            return 1;
        }else{
            return "服务器错误";
        }
    }

    public function getshopinfo($id)
    {
        $result = $this->where("id",$id)->find();
        return $result;
    }

    public function edit($data)
    {
        $validate = new ValidateShop();
        if(!$validate->scene('add')->check($data)){
            return $validate->getError();
        }
        $id = $data["id"];
        unset($data["id"]);
        $result = $this->save($data,["id"=>$id]);
        return 1;
    }

    public function deleteshop($id)
    {
        if(!is_array($id)){
            return "服务器错误";
        }
        foreach($id as $key=>$value){
            $this->where("id",$value)->delete();
        }
        return 1;
    }

    public function getshoporderlist($data)
    {
        $result = db("order")
            ->alias("o")
            ->join("app a", "a.appid=o.appid")
            ->join("shop s", "s.id=o.shop_id")
            ->join("user u", "u.id=o.userid")
            ->field("o.id,o.order_no,o.transaction_no,o.status,o.paymenttime,o.createtime,a.appname,s.name,s.price,s.payment,s.type,u.username")
            ->limit($data["limit"])->page($data["page"])
            ->order($data['sort'], $data['sortOrder'])
            ->select();
        $count = db("order")
            ->alias("o")
            ->join("app a", "a.appid=o.appid")
            ->join("shop s", "s.id=o.shop_id")
            ->join("user u", "u.id=o.userid")
            ->field("o.*")
            ->count();
        return json(["rows" => $result, "total" => $count]);
    }

    public function deleteorder($id)
    {
        if(!is_array($id)){
            return "服务器错误";
        }
        foreach($id as $key=>$value){
            db("order")->where("id",$value)->delete();
        }
        return 1;
    }

}
